package com.hj.tools;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期辅助类
 * @author HJ
 */
public class DateUtil {
	private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";
	
	private static final long ONE_MINUTE = 60000L;
    private static final long ONE_HOUR = 3600000L;
    private static final long ONE_DAY = 86400000L;
    private static final long ONE_WEEK = 604800000L;

    private static final String ONE_SECOND_AGO = "秒前";
    private static final String ONE_MINUTE_AGO = "分钟前";
    private static final String ONE_HOUR_AGO = "小时前";
    private static final String ONE_DAY_AGO = "天前";
    private static final String ONE_MONTH_AGO = "月前";
    private static final String ONE_YEAR_AGO = "年前";
	
	/**
	  * 得到本周周一
	  *
	  * @return yyyy-MM-dd
	  */
	 public static String getMondayOfThisWeek() {
	  Calendar c = Calendar.getInstance();
	  int dayofweek = c.get(Calendar.DAY_OF_WEEK) - 1;
	  if (dayofweek == 0){
		  dayofweek = 7;
	  }
	  c.add(Calendar.DATE, -dayofweek + 1);
	  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	  System.out.println("本周第一天="+sdf.format(c.getTime()));
	  return sdf.format(c.getTime());
	 }

	/**
	  *得到本周周日 
	  * @return yyyy-MM-dd
	  */
	 public static String getSundayOfThisWeek() {
	  Calendar c = Calendar.getInstance();
	  int dayofweek = c.get(Calendar.DAY_OF_WEEK) - 1;
	  if (dayofweek == 0){
		  dayofweek = 7;
	  }
	  c.add(Calendar.DATE, -dayofweek + 7);
	  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	  System.out.println(sdf.format(c.getTime()));
	  return sdf.format(c.getTime());
	 }

	/**
	  * 得到本月最后一天
	  *
	  * @return
	  */
	public static String getLastDateOfMonth() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date dt = new Date();
		Calendar cal = Calendar.getInstance();
		cal.setTime(dt);
		int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
		cal.set(Calendar.DAY_OF_MONTH, days);
		String result = format.format(cal.getTime());
		System.out.println("一个月最后一天" + result);
		return result;
	}

	 /**
	  * 得到本月第一天
	  *
	  * @return
	  */
	public static String getFristDateOfMonth() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date dt = new Date();
		Calendar cal = Calendar.getInstance();
		cal.setTime(dt);
		int days = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
		cal.set(Calendar.DAY_OF_MONTH, days);
		String result = format.format(cal.getTime());
		System.out.println("一个月第一天" + result);
		return result;
	}
	
	/**
	 * 获取从1900年到现在的天数
	 * @param ms 毫秒
	 * @return 16141天,8小时,21分钟,21秒,109毫秒 格式数据
	 */
	public static String getTimeDes(Long ms) {
        //处理参数为NULL的情况
        if(ms == null){
            return "";
        }
        int ss = 1000;
        int mi = ss * 60;
        int hh = mi * 60;
        int dd = hh * 24;

        long day = ms / dd;
        long hour = (ms - day * dd) / hh;
        long minute = (ms - day * dd - hour * hh) / mi;
        long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;
        
        StringBuilder str=new StringBuilder();
        if(day>0){
            str.append(day).append("天,");
        }
        if(hour>0){
            str.append(hour).append("小时,");
        }
        if(minute>0){
            str.append(minute).append("分钟,");
        }
        if(second>0){
            str.append(second).append("秒,");
        }
        if(milliSecond>0){
            str.append(milliSecond).append("毫秒,");
        }
        if(str.length()>0){
            str=str.deleteCharAt(str.length()-1);
        }

        return str.toString();
    }
	
	/**
	 * 日期类型转字符串类型
	 * 
	 * @param date
	 * @param dateFormat
	 * @return
	 */
	public static String dateToString(Date date, String dateFormat) {
		if (date == null)
			return "";
		try {
			return new SimpleDateFormat(dateFormat).format(date);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * 当前时间转字符串类型
	 * @param dateFormat
	 * @return
	 */
	public static String dateToString(String dateFormat) {
		try {
			return new SimpleDateFormat(dateFormat).format(new Date());
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	public static String dateToString() {
		try {
			return new SimpleDateFormat(DEFAULT_PATTERN).format(new Date());
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 日期类型转字符串类型，默认返回yyyy-MM-dd HH:mm:ss格式
	 * 
	 * @param date
	 * @return
	 */
	public static String dateToString(Date date) {
		return dateToString(date, DEFAULT_PATTERN);
	}
	
	/**
	 * 按照yyyy-MM-dd HH:mm:ss的格式，字符串转日期
	 * @param date
	 * @return
	 */
	public static Date stringToDate(String date){
		SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_PATTERN);
		try {
			return sdf.parse(date);
		} catch (ParseException e) {				
			e.printStackTrace();
		}
		return new Date();
	}
	
	/**
	 * 获取当前时间
	 */
	public static Date getCurrentDate(){
    	return new Date();
    }
	
	/**
	 * 获取时间戳
	 * @param dateStr 定义的时间 yyyy-MM-dd HH:mm:ss的格式
	 */
	public static long getMillisecond(String dateStr){
		long cur =  DateUtil.getCurrentDate().getTime();
    	long difine = DateUtil.stringToDate(dateStr).getTime();
    	return difine - cur;
	}
	
	public static void main(String[] args) throws IOException {
		//System.out.println(subDays(59));
		//synTime();
		URL url=new URL("http://bjtime.cn");//取得资源对象
       URLConnection uc=url.openConnection();//生成连接对象
       uc.connect(); //发出连接
       long ld=uc.getDate(); //取得网站日期时间
       Date date=new Date(ld); //转换为标准时间对象
       //分别取得时间中的小时，分钟和秒，并输出
       System.out.print(date.getHours()+"时"+date.getMinutes()+"分"+date.getSeconds()+"秒");
	}
	
	public static void synTime() {
        new Thread(new Runnable() {
 
            @Override
            public void run() {
                try {
                    URL url = new URL("http://bjtime.cn/");// 取得资源对象
                    URLConnection uc = url.openConnection();// 生成连接对象
                    uc.setConnectTimeout(2000);
                    uc.connect(); // 发出连接
                    Calendar calendar = Calendar.getInstance();
                    long timeStamp = uc.getDate();
                    calendar.setTimeInMillis(timeStamp);
 
                    String command = String.format("date -s %d%02d%02d.%02d%02d%02d", calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
                    System.out.println(command);
                    // 运行Shell
                    //Commons.execShell(command);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
	
	/**
	 * 日期天数相减
	 * @param days
	 */
	public static String subDays(int days){
		Calendar calendar=Calendar.getInstance();  
	    calendar.setTime(new Date());
	    calendar.set(Calendar.DAY_OF_MONTH, (calendar.get(Calendar.DAY_OF_MONTH)+days));  
	    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	    return format.format(calendar.getTime());
	}
	
	/**
	 * 获取日期和周末
	 * @return 2014年9月25日 星期四
	 */
	public static String getDateAndWeek(){
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL);
		return dateFormat.format(date);
	}
	
	public static String format(Date date) {
        long delta = new Date().getTime() - date.getTime();
        if (delta < 1L * ONE_MINUTE) {
            long seconds = toSeconds(delta);
            return (seconds <= 0 ? 1 : seconds) + ONE_SECOND_AGO;
        }
        if (delta < 45L * ONE_MINUTE) {
            long minutes = toMinutes(delta);
            return (minutes <= 0 ? 1 : minutes) + ONE_MINUTE_AGO;
        }
        if (delta < 24L * ONE_HOUR) {
            long hours = toHours(delta);
            return (hours <= 0 ? 1 : hours) + ONE_HOUR_AGO;
        }
        if (delta < 48L * ONE_HOUR) {
            return "昨天";
        }
        if (delta < 30L * ONE_DAY) {
            long days = toDays(delta);
            return (days <= 0 ? 1 : days) + ONE_DAY_AGO;
        }
        if (delta < 12L * 4L * ONE_WEEK) {
            long months = toMonths(delta);
            return (months <= 0 ? 1 : months) + ONE_MONTH_AGO;
        } else {
            long years = toYears(delta);
            return (years <= 0 ? 1 : years) + ONE_YEAR_AGO;
        }
    }

    private static long toSeconds(long date) {
        return date / 1000L;
    }

    private static long toMinutes(long date) {
        return toSeconds(date) / 60L;
    }

    private static long toHours(long date) {
        return toMinutes(date) / 60L;
    }

    private static long toDays(long date) {
        return toHours(date) / 24L;
    }

    private static long toMonths(long date) {
        return toDays(date) / 30L;
    }

    private static long toYears(long date) {
        return toMonths(date) / 365L;
    }
}
